package chaos.control;

import com.jme.input.InputHandler;
import com.jme.input.KeyBindingManager;
import com.jme.input.KeyInput;
import com.jme.input.RelativeMouse;
import com.jme.input.action.KeyNodeBackwardAction;
import com.jme.input.action.KeyNodeForwardAction;
import com.jme.input.action.KeyNodeLookDownAction;
import com.jme.input.action.KeyNodeLookUpAction;
import com.jme.input.action.KeyNodeRotateLeftAction;
import com.jme.input.action.KeyNodeRotateRightAction;
import com.jme.input.action.KeyNodeStrafeLeftAction;
import com.jme.input.action.KeyNodeStrafeRightAction;
import com.jme.input.action.NodeMouseLook;
import com.jme.math.Vector3f;
import com.jme.renderer.Camera;
import com.jme.scene.CameraNode;
import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.system.DisplaySystem;

public class CBFThirdPersonController extends InputHandler {
	public static final String FORWARD = "forward:kb:cbf";
	public static final String BACKWARD = "backward:kb:cbf";
	public static final String STRAFELEFT = "left:kb:cbf";
	public static final String STRAFERIGHT = "right:kb:cbf";
	public CameraNode cameraNode = null;
	
    public CBFThirdPersonController(Node rootNode, Camera camera, float keySpeed, float mouseSpeed) {
    	cameraNode = new CameraNode("CBF:ThirdPersonController", camera);
    	cameraNode.setLocalTranslation(new Vector3f(0, 0, -250));
        cameraNode.updateWorldData(0);
        setKeyBinding();
        setUpMouse(cameraNode, mouseSpeed );
        setActions(cameraNode, keySpeed, mouseSpeed );
        rootNode.attachChild(cameraNode);
    }

    private void setKeyBinding() {
        KeyBindingManager keyboard = KeyBindingManager.getKeyBindingManager();
        keyboard.set(FORWARD, KeyInput.KEY_W);
        keyboard.set(BACKWARD, KeyInput.KEY_S);
        keyboard.set(STRAFELEFT, KeyInput.KEY_A);
        keyboard.set(STRAFERIGHT, KeyInput.KEY_D);
    }

    private void setUpMouse( Spatial node, float mouseSpeed ) {
        RelativeMouse mouse = new RelativeMouse("Mouse Input");
        mouse.registerWithInputHandler( this );
        NodeMouseLook mouseLook = new NodeMouseLook(mouse, node, 0.1f);
        mouseLook.setSpeed( mouseSpeed );
        mouseLook.setLockAxis(new Vector3f(node.getLocalRotation().getRotationColumn(1).x,
                node.getLocalRotation().getRotationColumn(1).y,
                node.getLocalRotation().getRotationColumn(1).z));
        addAction(mouseLook);
    }
    
    private void setActions( Spatial node, float moveSpeed, float turnSpeed ) {
        addAction( new KeyNodeForwardAction( node, moveSpeed ), FORWARD, true );
        addAction( new KeyNodeBackwardAction( node, moveSpeed ), BACKWARD, true );
        addAction( new KeyNodeStrafeLeftAction( node, moveSpeed ), STRAFELEFT, true );
        addAction( new KeyNodeStrafeRightAction( node, moveSpeed ), STRAFERIGHT, true );
    }
}
